package com.wc.alorithm_luogu.P1065;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * @Author congge
 * @Date 2023/4/26 19:22
 * @description https://www.luogu.com.cn/problem/P1065
 * 作业调度方案
 */
public class Main {
    public static void main(String[] args) {
        // 存储所有阶乘的数
        ArrayList<BigDecimal> floorMul = new ArrayList<>();
        BigDecimal bigDecimal0 = new BigDecimal(1);
        BigDecimal bigDecimal1 = new BigDecimal(1);
        floorMul.add(bigDecimal0);
        floorMul.add(bigDecimal1);
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        ArrayList<Integer> ans = new ArrayList<>();
        while (n-- > 0) {
            int x = sc.nextInt();
            int num = sc.nextInt();

            int size = floorMul.size();
            // 如果阶乘超过了floorMul的大小说明还未计算
            if (x >= floorMul.size()) {
                for (int i = size; i <= x; i++) {
                    BigDecimal bigDecimalX = new BigDecimal(i);
                    bigDecimalX = bigDecimalX.multiply(floorMul.get(i - 1));
                    floorMul.add(bigDecimalX);
                }
            }
            BigDecimal curNum = floorMul.get(x);
            String s = curNum.toString();
            int ansNum = 0;
            for (char ch : s.toCharArray()) {
                if ((ch - '0') == num) {
                    ansNum++;
                }
            }
            ans.add(ansNum);
        }

        int size = ans.size();
        for (Integer an : ans) {
            System.out.println(an);
        }
    }
}
